package com.mojian.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipaySystemOauthTokenRequest;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.response.AlipaySystemOauthTokenResponse;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.mojian.common.Result;
import com.mojian.config.AlipayConfig;
import com.mojian.entity.PayOrder;
import com.mojian.mapper.PayOrderMapper;
import com.mojian.model.vo.PayOrderVO;
import com.mojian.service.PaymentService;
import com.mojian.util.SpringContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.PostConstruct;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * 支付测试控制器
 * 仅用于调试支付宝配置问题
 */
@RestController
@RequestMapping("/payment/test")
@Slf4j
public class PaymentTestController {

    @Autowired
    private AlipayClient alipayClient;

    @Autowired
    private AlipayConfig alipayConfig;

    @PostConstruct
    public void init() {
        log.info("支付测试控制器初始化");
    }

    /**
     * 显示沙箱账号信息
     */
    @GetMapping("/sandbox-info")
    public Result<Map<String, Object>> getSandboxInfo() {
        Map<String, Object> info = new HashMap<>();
        
        // 应用信息
        Map<String, String> appInfo = new HashMap<>();
        appInfo.put("appId", alipayConfig.getAppId());
        appInfo.put("gatewayUrl", alipayConfig.getGatewayUrl());
        appInfo.put("charset", alipayConfig.getCharset());
        appInfo.put("signType", alipayConfig.getSignType());
        info.put("appInfo", appInfo);
        
        // 商家账号
        Map<String, String> merchantInfo = new HashMap<>();
        merchantInfo.put("account", "mqddkk7093@sandbox.com");
        merchantInfo.put("password", "111111");
        merchantInfo.put("pid", "2088721070767195");
        info.put("merchantInfo", merchantInfo);
        
        // 买家账号
        Map<String, String> buyerInfo = new HashMap<>();
        buyerInfo.put("account", "jhcipk9186@sandbox.com");
        buyerInfo.put("password", "111111");
        buyerInfo.put("payPassword", "111111");
        buyerInfo.put("uid", "2088722070793313");
        info.put("buyerInfo", buyerInfo);
        
        return Result.success(info);
    }

    /**
     * 测试支付宝配置是否正确
     */
    @GetMapping("/alipay-config")
    public Result<Map<String, Object>> testAlipayConfig() {
        Map<String, Object> result = new HashMap<>();
        
        log.info("========== 开始测试支付宝配置 ==========");
        log.info("支付宝应用ID: {}", alipayConfig.getAppId());
        log.info("支付宝网关URL: {}", alipayConfig.getGatewayUrl());
        log.info("字符编码: {}", alipayConfig.getCharset());
        log.info("签名类型: {}", alipayConfig.getSignType());
        
        result.put("appId", alipayConfig.getAppId());
        result.put("gatewayUrl", alipayConfig.getGatewayUrl());
        result.put("charset", alipayConfig.getCharset());
        result.put("signType", alipayConfig.getSignType());
        
        // 尝试简单的API调用测试连接
        try {
            AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();
            request.setGrantType("authorization_code");
            request.setCode("dummy_code"); // 这是一个无效代码，但可以测试基本连接和签名
            
            log.info("尝试调用支付宝API...");
            AlipaySystemOauthTokenResponse response = alipayClient.execute(request);
            
            log.info("支付宝API响应: code={}, msg={}, subCode={}, subMsg={}", 
                response.getCode(), response.getMsg(), response.getSubCode(), response.getSubMsg());
            
            result.put("testResult", "已连接支付宝API");
            
            // 使用HashMap创建嵌套Map
            Map<String, String> apiResponse = new HashMap<>();
            apiResponse.put("code", response.getCode());
            apiResponse.put("msg", response.getMsg());
            apiResponse.put("subCode", response.getSubCode());
            apiResponse.put("subMsg", response.getSubMsg());
            
            result.put("apiResponse", apiResponse);
            
            return Result.success(result);
        } catch (AlipayApiException e) {
            log.error("支付宝API调用失败", e);
            result.put("testResult", "支付宝API调用失败");
            result.put("errorMessage", e.getMessage());
            return Result.success(result);
        } catch (Exception e) {
            log.error("测试过程中发生异常", e);
            return Result.error("测试失败: " + e.getMessage());
        }
    }
    
    /**
     * 测试创建支付宝订单
     */
    @PostMapping("/create-order")
    public Result<Map<String, Object>> testCreateOrder(@RequestBody(required = false) Map<String, Object> params) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            log.info("========== 开始测试创建支付宝订单 ==========");
            
            // 默认参数
            String outTradeNo = "TEST_" + System.currentTimeMillis();
            String totalAmount = "0.01";
            String subject = "测试商品";
            
            // 如果有传入参数，则使用传入的参数
            if (params != null) {
                if (params.containsKey("outTradeNo")) {
                    outTradeNo = params.get("outTradeNo").toString();
                }
                if (params.containsKey("totalAmount")) {
                    totalAmount = params.get("totalAmount").toString();
                }
                if (params.containsKey("subject")) {
                    subject = params.get("subject").toString();
                }
            }
            
            log.info("订单参数: outTradeNo={}, totalAmount={}, subject={}", 
                    outTradeNo, totalAmount, subject);
            
            // 创建预下单请求
            AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();
            request.setNotifyUrl(alipayConfig.getNotifyUrl());
            
            // 构建业务参数
            JSONObject bizContent = new JSONObject();
            bizContent.put("out_trade_no", outTradeNo);
            bizContent.put("total_amount", totalAmount);
            bizContent.put("subject", subject);
            bizContent.put("body", "测试订单");
            bizContent.put("timeout_express", "15m");
            
            request.setBizContent(bizContent.toString());
            
            log.info("调用支付宝预下单接口...");
            log.info("请求参数: {}", bizContent.toString());
            
            // 执行请求
            AlipayTradePrecreateResponse response = alipayClient.execute(request);
            
            log.info("支付宝响应: success={}, code={}, msg={}", 
                    response.isSuccess(), response.getCode(), response.getMsg());
            
            result.put("success", response.isSuccess());
            result.put("code", response.getCode());
            result.put("msg", response.getMsg());
            
            if (response.isSuccess()) {
                String qrCode = response.getQrCode();
                log.info("获取到二维码内容: {}", qrCode);
                
                // 生成二维码图片URL
                String qrCodeUrl = "https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=" + qrCode;
                
                result.put("qrCode", qrCode);
                result.put("qrCodeUrl", qrCodeUrl);
                
                // 构建支付订单VO对象，方便前端处理
                PayOrderVO orderVO = new PayOrderVO();
                orderVO.setOrderNo(outTradeNo);
                orderVO.setAmount(new BigDecimal(totalAmount));
                orderVO.setStatus("PENDING");
                orderVO.setQrCodeUrl(qrCodeUrl);
                
                result.put("orderVO", orderVO);
                
                // 添加沙箱测试账号信息，方便测试
                Map<String, String> sandboxInfo = new HashMap<>();
                sandboxInfo.put("buyerAccount", "jhcipk9186@sandbox.com");
                sandboxInfo.put("buyerPassword", "111111");
                sandboxInfo.put("payPassword", "111111");
                result.put("sandboxInfo", sandboxInfo);
                
                return Result.success(result);
            } else {
                log.error("创建订单失败: subCode={}, subMsg={}", 
                        response.getSubCode(), response.getSubMsg());
                
                result.put("subCode", response.getSubCode());
                result.put("subMsg", response.getSubMsg());
                
                // 修复类型不匹配问题
                Result<Map<String, Object>> errorResult = new Result<>();
                errorResult.setCode(500);
                errorResult.setMessage(response.getSubMsg());
                errorResult.setData(result);
                return errorResult;
            }
            
        } catch (Exception e) {
            log.error("测试创建订单异常", e);
            // 修复类型不匹配问题
            Result<Map<String, Object>> errorResult = new Result<>();
            errorResult.setCode(500);
            errorResult.setMessage("测试失败: " + e.getMessage());
            return errorResult;
        }
    }

    /**
     * 手动更新订单状态为成功
     * 仅用于测试，生产环境不应使用
     */
    @PostMapping("/update-order-status")
    public Result<Map<String, Object>> updateOrderStatus(@RequestBody Map<String, Object> params) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            log.info("========== 开始手动更新订单状态 ==========");
            
            // 获取订单号
            String orderNo = params.get("orderNo").toString();
            if (orderNo == null || orderNo.isEmpty()) {
                return Result.error("订单号不能为空");
            }
            
            log.info("手动更新订单状态: orderNo={}", orderNo);
            
            // 构建支付宝异步通知参数
            Map<String, String> notifyParams = new HashMap<>();
            notifyParams.put("out_trade_no", orderNo);
            notifyParams.put("trade_no", "TEST_TRADE_" + System.currentTimeMillis());
            notifyParams.put("trade_status", "TRADE_SUCCESS");
            notifyParams.put("total_amount", params.getOrDefault("amount", "1.00").toString());
            notifyParams.put("gmt_payment", System.currentTimeMillis() + "");
            notifyParams.put("seller_id", "2088721070767195");
            notifyParams.put("buyer_id", "2088722070793313");
            
            // 调用订单服务更新状态
            try {
                // 注入PaymentService
                PaymentService paymentService = SpringContextUtil.getBean(PaymentService.class);
                if (paymentService != null) {
                    // 更新订单状态
                    paymentService.handleAlipayNotify(notifyParams);
                    
                    // 查询最新状态
                    Result<PayOrderVO> orderResult = paymentService.checkOrderStatus(orderNo);
                    if (orderResult.getCode() == 200 && orderResult.getData() != null) {
                        result.put("orderStatus", orderResult.getData().getStatus());
                    } else {
                        result.put("orderStatus", "未知");
                    }
                    
                    result.put("success", true);
                    result.put("message", "订单状态已更新");
                } else {
                    result.put("success", false);
                    result.put("message", "无法获取PaymentService");
                }
            } catch (Exception e) {
                log.error("更新订单状态异常", e);
                result.put("success", false);
                result.put("message", "更新订单状态异常: " + e.getMessage());
            }
            
            return Result.success(result);
        } catch (Exception e) {
            log.error("手动更新订单状态异常", e);
            return Result.error("操作失败: " + e.getMessage());
        }
    }

    /**
     * 手动设置订单状态
     * 仅用于测试，生产环境不应使用
     */
    @PostMapping("/set-order-status")
    public Result<Map<String, Object>> setOrderStatus(@RequestBody Map<String, Object> params) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            log.info("========== 开始手动设置订单状态 ==========");
            
            // 获取参数
            String orderNo = params.get("orderNo").toString();
            String status = params.get("status").toString();
            
            if (orderNo == null || orderNo.isEmpty()) {
                return Result.error("订单号不能为空");
            }
            
            if (status == null || status.isEmpty()) {
                status = "SUCCESS"; // 默认设置为成功状态
            }
            
            log.info("手动设置订单状态: orderNo={}, status={}", orderNo, status);
            
            // 查询订单
            PayOrderMapper payOrderMapper = SpringContextUtil.getBean(PayOrderMapper.class);
            if (payOrderMapper == null) {
                return Result.error("无法获取PayOrderMapper");
            }
            
            PayOrder payOrder = payOrderMapper.selectOne(
                new LambdaQueryWrapper<PayOrder>()
                    .eq(PayOrder::getOrderNo, orderNo)
            );
            
            if (payOrder == null) {
                return Result.error("订单不存在: " + orderNo);
            }
            
            // 更新订单状态
            payOrder.setStatus(status);
            payOrder.setUpdateTime(LocalDateTime.now());
            
            if ("SUCCESS".equals(status)) {
                payOrder.setTradeNo("TEST_" + System.currentTimeMillis());
                payOrder.setPayTime(LocalDateTime.now());
            }
            
            int rows = payOrderMapper.updateById(payOrder);
            log.info("订单状态已更新: 影响行数={}", rows);
            
            // 返回结果
            result.put("success", true);
            result.put("message", "订单状态已更新为: " + status);
            result.put("orderNo", orderNo);
            result.put("status", status);
            result.put("articleId", payOrder.getArticleId());
            result.put("userId", payOrder.getUserId());
            
            return Result.success(result);
        } catch (Exception e) {
            log.error("手动设置订单状态异常", e);
            return Result.error("操作失败: " + e.getMessage());
        }
    }
} 